// pages/Index/myShopCircleCoupon.js
const controller = require("../controllers/Controller").controller

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList: [{
      text: "一卡通券",
      type: 0,
      num: ""
    }, {
      text: "我的爆品",
      type: 2,
      num: ""
    }, {
      text: "欢乐拼",
      type: 3,
      num: ""
    }, {
      text: "超值抵扣券",
      type: 4,
      num: ""
    }, {
      text: "超值礼包",
      type: 5,
      num: ""
    }],
    activityType: 0,
    selectIndex: 0,
    couponType: 1,
    myList: [],
    isOther: false,
    shopDetail: "",
    couponState: 0,
    couponStates: "",
    pageNumber: 1,
    lastPage: false,

    List: [],
    lastPage: false,
    otherList: [],
    otherLastPage: false,
    otherPageNumber: 1,
    isGive: false,
    accountCouponBagId: '',
    maxGiveNum: 0,
    giveNum: null,
    couponTypeList: ["一卡通", "他人赠送一卡通", "他人赠送优惠券"],
    couponCurrentIndex: 0
  },

  //跳转领券中心
  // toReceiveCenter(){
  //   wx.navigateTo({
  //     url: '/pages/Mall/Coupon',
  //   })
  // },

  // 一卡通类型选择
  couponListChange(e) {
    let index = e.currentTarget.dataset.index

    this.setData({
      couponCurrentIndex: index,
    })
    switch (index) {
      case 0:
        this.getMyList(true);
        break;
      case 1:
        this.getMyList(true, 1);
        break;
      case 2:
        this.othersGiveGroupCouponPage(true)
        break;
    }

  },

  // 使用记录
  useHistory(e) {
    const type = e.currentTarget.dataset.type
    const accountcouponbagid = e.currentTarget.dataset.accountcouponbagid
    wx.navigateTo({
      url: '/pages/myCenter/useRecord?accountCouponBagId=' + accountcouponbagid + "&type=" + type,
    })
  },
  //核销爆品
  writeOffGoods(e) {
    let value = {}
    value.accountCouponBagId = e.currentTarget.dataset.accountcouponbagid
    controller.HotBagQrCode(value).then(res => {
      console.log(res.data.qrCode);
      if (res.data.qrCode) {
        wx.previewImage({
          urls: [res.data.qrCode],
        })
      }

    })
  },
  //赠送他人弹窗
  give(e) {
    const ismail = e.target.dataset.ismail // isMail=1 的爆款 无法赠送
    console.log(ismail);
    if (ismail == 1) {
      wx.showToast({
        title: '直邮到家无法赠送',
        icon: 'none'
      })
      return
    }
    console.log(e);
    this.setData({
      isGive: true,
      maxGiveNum: e.target.dataset.num,
      accountCouponBagId: e.target.dataset.accountcouponbagid,
      giveImg: e.target.dataset.giveimg || e.target.dataset.img
    })
  },

  inputNum(e) {
    let giveNum = e.detail.value
    const maxGiveNum = this.data.maxGiveNum
    if (giveNum == '' || (giveNum > 0 && giveNum <= maxGiveNum)) {
      this.setData({
        giveNum
      })
    } else {
      wx.showToast({
        title: '请正确填写数量',
        icon: 'none',
        duration: 1500
      });
      this.setData({
        giveNum: 1
      })
    }
  },
  closeDialog() {
    this.setData({
      isGive: false,
      giveNum: null
    })
  },
  //获取个人中心数据
  getMyInformation() {
    let value = {}
    value.shopId = wx.getStorageSync('shopId')
    controller.myInformation(value).then(res => {
      let list = this.data.tabList
      list[0].num = res.data.couponNum
      list[1].num = res.data.giftNum
      list[2].num = res.data.pinNum
      list[3].num = res.data.limitNum
      list[4].num = res.data.drainageNum
      this.setData({
        tabList: list
      })

    })
  },

  //跳转券详情
  // toDetail(e) {
  //   let id = e.currentTarget.dataset.id
  //   let couponAccountId = e.currentTarget.dataset.haveid
  //   let couponType = e.currentTarget.dataset.paytype
  //   let couponBagId = e.currentTarget.dataset.couponbagid
  //   let shopId = e.currentTarget.dataset.shopid
  //   if (couponType == 0) {
  //     wx.navigateTo({
  //       url: '/pages/Mall/Coupondetail?id=' + id + "&couponAccountId=" + couponAccountId + "&couponType=0"+ "&shopId=" + shopId,
  //     })
  //   } else {
  //     wx.navigateTo({
  //       url: '/pages/Mall/couponDetailBuy?id=' + id + "&couponAccountId=" + couponAccountId + '&couponBagId=' + couponBagId + "&out=1" + "&shopId=" + shopId,
  //     })
  //   }
  // },

  //切换tab
  changeTab(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      selectIndex: index,
      couponCurrentIndex:0,
      activityType: this.data.tabList[index].type
    })
    this.getMyList(true)
  },

  //获取优惠券列表
  // getCouponList() {
  //   let value = {}
  //   value.shopId = wx.getStorageSync('shopId')
  //   value.couponType = this.data.couponType
  //   value.couponState = this.data.couponState
  //   value.couponStates = this.data.couponStates
  //   controller.getCouponList(value).then(res => {
  //     res.data.my.forEach(item => {
  //       if (item.effectiveStartTime) {
  //         item.effectiveStartTime = item.effectiveStartTime.split(" ")[0]
  //         item.effectiveEndTime = item.effectiveEndTime.split(" ")[0]
  //       }
  //     })

  //     res.data.other.forEach(item => {
  //       if (item.effectiveStartTime) {
  //         item.effectiveStartTime = item.effectiveStartTime.split(" ")[0]
  //         item.effectiveEndTime = item.effectiveEndTime.split(" ")[0]
  //       }
  //     })
  //     this.setData({
  //       list: res.data.my,
  //       otherList: res.data.other
  //     })
  //   })
  // },

  //跳转一卡通他人赠送优惠券详情
  toCouponDetail(e) {
    let id = e.currentTarget.dataset.id
    let couponAccountId = e.currentTarget.dataset.couponaccountid
    let couponBagId = e.currentTarget.dataset.couponbagid
    let shopId = e.currentTarget.dataset.shopid
    wx.navigateTo({
      url: '/pages/couponBagCenter/couponDetail?id=' + id + "&couponAccountId=" + couponAccountId + '&couponBagId=' + couponBagId + "&shopId=" + shopId + "&isReceive=" + false,
    })

  },

  // 自己购买的活动列表
  async getMyList(isFirst = false, giveType = 0) {
    if (isFirst) {
      this.setData({
        pageNumber: 1,
        list: []
      })
      const selectIndex = this.data.selectIndex
      if (selectIndex == 1 || selectIndex == 3) this.getGiveList(true)
    }
    const pageNumber = this.data.pageNumber
    let {
      list,
      lastPage
    } = await this.getList(pageNumber, giveType)

    list = this.data.list.concat(list)

    this.setData({
      list,
      lastPage: lastPage,
      pageNumber: pageNumber + 1
    })
  },
  // 他人赠送的活动列表
  async getGiveList(isFirst = false) {
    if (isFirst) {
      this.setData({
        otherPageNumber: 1,
        otherList: []
      })
    }
    const otherPageNumber = this.data.otherPageNumber
    let {
      list,
      lastPage
    } = await this.getList(otherPageNumber, 1)
    list = this.data.otherList.concat(list)

    this.setData({
      otherList: list,
      otherLastPage: lastPage,
      otherPageNumber: otherPageNumber + 1
    })
  },
  // 获取活动列表
  async getList(pageNumber, giveType) {
    let value = {}
    value.giveType = giveType
    value.pageNumber = pageNumber
    value.type = this.data.activityType
    value.shopId = wx.getStorageSync('shopId')
    const res = await controller.getBagList(value)
    res.data.list.forEach(item => {
      if (item.effectiveStartTime) {
        item.effectiveStartTime = item.effectiveStartTime.split(" ")[0].replace(/-/g, '.')
        item.effectiveEndTime = item.effectiveEndTime.split(" ")[0].replace(/-/g, '.')
      }
    })

    return {
      list: res.data.list,
      lastPage: res.data.lastPage,
    }
  },

  // 一卡通--他人赠送的优惠券列表
  async othersGiveGroupCouponPage(isFirst = false) {
    if (isFirst) {
      this.setData({
        pageNumber: 1,
        list: []
      })
    }
    let pageNumber = this.data.pageNumber
    let shopId = wx.getStorageSync('shopId')
    let value = {
      shopId,
      pageNumber
    }
    const res = await controller.othersGiveGroupCouponPage(value)
    res.data.list.forEach(item => {
      if (item.effectiveStartTime) {
        item.effectiveStartTime = item.effectiveStartTime.split(" ")[0].replace(/-/g, '.')
        item.effectiveEndTime = item.effectiveEndTime.split(" ")[0].replace(/-/g, '.')
      }
    })
    const list = this.data.list.concat(res.data.list)

    this.setData({
      list,
      lastPage: res.data.lastPage,
      pageNumber: pageNumber + 1
    })
  },

  handleShowDelClick() {
    let showDel = this.data.showDel
    showDel = !showDel
    this.setData({
      showDel
    })
  },

  //跳转券包详情
  toDetail(e) {
    let id = e.currentTarget.dataset.id
    let orderNo = e.currentTarget.dataset.orderno || ''
    let couponAccountId = e.currentTarget.dataset.haveid
    let couponType = e.currentTarget.dataset.paytype
    let couponBagId = e.currentTarget.dataset.couponbagid
    let shopId = e.currentTarget.dataset.shopid || wx.getStorageSync('shopId')
    let accountCouponBagId = e.currentTarget.dataset.accountcouponbagid


    if (this.data.activityType == 0) {
      wx.navigateTo({
        url: '/pages/myCenter/couponBagDetail?id=' + id + "&orderNo=" + orderNo + "&shopId=" + shopId+ "&accountCouponBagId=" + accountCouponBagId,
      })
    } else if (this.data.activityType == 2 || this.data.activityType == 3 || this.data.activityType == 5) {
      wx.navigateTo({
        url: '/pages/myCenter/tradingAreaDetail?id=' + id + '&orderNo=' + orderNo + "&type=" + this.data.activityType + "&accountCouponBagId=" + accountCouponBagId + "&shopId=" + shopId,
      })
    } else {
      wx.navigateTo({
        url: '/pages/couponBagCenter/limitCouponDetail?id=' + id + "&shopId=" + shopId + "&accountCouponBagId=" + accountCouponBagId,
      })
    }
  },

  //删除活动
  delActivity(e) {
    let value = {}
    value.orderNo = e.currentTarget.dataset.orderno
    wx.showModal({
      title: "是否删除该活动",
      success: (res) => {
        if (res.confirm) {
          controller.delAccountBag(value).then(res => {
            this.setData({
              'value.pageNumber': 1
            })
            this.getMyList(true)
          })
        }
      }
    })

  },

  //获取店铺详情
  // getShopDetail(){
  //   controller.shopDetails({shopId:wx.getStorageSync('shopId')}).then(res=>{
  //     this.setData({
  //       shopDetail:res.data
  //     })
  //   })
  // },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getMyList(true)
    this.getMyInformation()
    // this.getShopDetail()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.lastPage) {
      const index = this.data.couponCurrentIndex
      switch (index) {
        case 0:
          this.getMyList();
          break;
        case 1:
          this.getMyList(false, 1)
          break;
        case 2:
          this.othersGiveGroupCouponPage()
          break;
      }
    }
    if (!this.data.otherLastPage) {
      const selectIndex = this.data.selectIndex
      if (selectIndex == 1 && selectIndex == 3) {
        this.getGiveList()
      }
    }
  },


  /**
   * 用户点击右上角分享
   */
  async onShareAppMessage(e) {
    this.setData({
      showDel: false,
    })

    const type = this.data.activityType
    console.log(type);
    let num = 1
    let accountCouponBagId = null
    let giveImg = null
    if (type == 0 || type == 2) {
      num = this.data.giveNum ? this.data.giveNum : 1
      accountCouponBagId = this.data.accountCouponBagId
      giveImg = this.data.giveImg
    } else if (type == 4) {
      accountCouponBagId = e.target.dataset.accountcouponbagid
      giveImg = e.target.dataset.giveimg || e.target.dataset.img
    }
    console.log(accountCouponBagId, num, giveImg);
    let value = {
      accountCouponBagId,
      num
    }
    // 创建领取码
    const res = await controller.createGiveCode(value)
    const code = res.data
    // 私密转发
    wx.updateShareMenu({
      withShareTicket: true,
      isPrivateMessage: true,
      activityId: accountCouponBagId,
    })
    return {
      title: '好友赠送',
      path: '/pages/myCenter/receiveCoupon?accountCouponBagId=' + accountCouponBagId + '&code=' + code + '&num=' + num + '&type=' + type,
      imageUrl: giveImg,
    }
  }
})